import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

import type {
  CountStateType,
  CountStateActionType,
  LanguageType,
  LanguageStateType,
  LanguageStateActionType,
  ThemeType,
  ThemeStateType,
  ThemeStateActionType,
  MetaStateType,
  MetaStateActionType,
  MenuStateType,
  MenuStateActionType,
  RefreshStateType,
  RefreshStateActionType,
  AppConfigStateType,
  AppConfigStateActionType,
  UserAuthStateType,
  UserAuthStateActionType,
  MailTypeOptionsStateType,
  MailTypeOptionsStateActionType,
  MailTemplatesStateType,
  MailTemplatesStateActionType,
  CookiesStateType,
  CookiesStateActionType,
  LogStateType,
  LogStateActionType,
} from '@/types/stores.type'

// 示例
/** 计数状态存储 */
const useCountState = create<CountStateType & CountStateActionType>()(
  persist(
    (set, get) => ({
      count: 0,
      addCount: () => set({ count: get().count + 1 }),
    }),
    {
      name: 'count-storage', // 存储的名称、必须唯一
      storage: createJSONStorage(() => sessionStorage),
      // name: 存储中使用的唯一键名
      // storage: 自定义存储引擎
      // partialize: 选择存储部分状态字段
      // onRehydrateStorage: 在存储被重新加载之后触发
      // version: 版本控制
      // migrate: 处理版本迁移的函数
      // merge: 自定义持久化的值与当前状态的合并方式
      // skipHydration: 是否跳过初始化时的自动恢复
    }
  )
)

/** 语言状态存储 */
const useLanguage = create<LanguageStateType & LanguageStateActionType>()(
  persist(
    (set) => ({
      language: 'zh-CN',
      setLanguage: (language: LanguageType) => set({ language }),
      resetLanguage: () => set({ language: 'zh-CN' }),
    }),
    {
      name: 'language-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
)

/** 主题状态存储 */
const useTheme = create<ThemeStateType & ThemeStateActionType>()(
  persist(
    (set) => ({
      theme: 'light',
      setTheme: (theme: ThemeType) => set({ theme }),
      resetTheme: () => set({ theme: 'light' }),
    }),
    {
      name: 'theme-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
)

/** 元数据存储 */
const useMeta = create<MetaStateType & MetaStateActionType>()(
  persist(
    (set, _) => ({
      meta: {
        title: '',
        keywords: '',
        description: '',
      },
      setMeta: (title: string, keywords?: string, description?: string) => {
        document.title = title
        set({
          meta: {
            title,
            keywords: keywords || title,
            description: description || title,
          }
        })
      },
    }),
    {
      name: 'meta-storage',
      storage: createJSONStorage(() => sessionStorage),
    }
  )
)

/** 菜单键存储 */
const useMenuKey = create<MenuStateType & MenuStateActionType>()(
  persist(
    (set, _) => ({
      menuKey: '/home',
      setMenuKey: (menuKey: string) => set({ menuKey }),
    }),
    {
      name: 'menu-key-storage',
      storage: createJSONStorage(() => sessionStorage),
    }
  )
)

/** 刷新模块存储 */
const useRefresh = create<RefreshStateType & RefreshStateActionType>((set) => ({
  refreshModules: [],
  setRefresh: (refreshModules?: string[] | false | undefined) => set(() => {
    return {
      refreshModules: refreshModules || [],
    }
  }),
}))

/** 应用配置存储 */
const useAppConfig = create<AppConfigStateType & AppConfigStateActionType>()(
  persist(
    (set, _) => ({
      appConfig: {
        language: 'zh-CN',
        theme: 'blue',
        darkMode: false,
        homeModules: ['todo', 'note', 'review'],
      },
      setAppConfig: (appConfig: AppConfigStateType['appConfig']) => set({
        appConfig
      }),
    }),
    {
      name: 'app-config-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
)

/** 权限配置存储 */
const useUserAuth = create<UserAuthStateType & UserAuthStateActionType>()(
  persist(
    (set, _) => ({
      userAuth: {
        authType: 'JWT',
      },
      setAuthConfig: (userAuth: UserAuthStateType) => set(userAuth),
    }),
    {
      name: 'auth-config-storage',
      storage: createJSONStorage(() => sessionStorage),
    }
  )
)

/** 邮件类型字典存储 */
const useMailTypeOptions = create<MailTypeOptionsStateType & MailTypeOptionsStateActionType>((set) => ({
  mailTopTypeOptions: [],
  mailSecondTypeOptions: [],
  setMailTopTypeOptions: (mailTopTypeOptions: MailTypeOptionsStateType['mailTopTypeOptions']) => set({ mailTopTypeOptions }),
  setMailSecondTypeOptions: (mailSecondTypeOptions: MailTypeOptionsStateType['mailSecondTypeOptions']) => set({ mailSecondTypeOptions })
}))

/** 模板存储 */
const useMailTemplates = create<MailTemplatesStateType & MailTemplatesStateActionType>((set) => ({
  mailTemplates: [],
  setMailTemplates: (mailTemplates: MailTemplatesStateType['mailTemplates']) => set({ mailTemplates })
}))

/** Cookies 存储 */
const useCookies = create<CookiesStateType & CookiesStateActionType>((set) => ({
  JSYCookie: '',
  setJSYCookie: (JSYCookie: CookiesStateType['JSYCookie']) => set({ JSYCookie })
}))

/** 日志存储 */
const useLog = create<LogStateType & LogStateActionType>((set) => ({
  log: [],
  setLog: async (log: LogStateType['log'], operation: 'overwrite' | 'append' = 'append') => {
    set((state => ({
      log: operation === 'append' ? state.log.concat(log) : log
    })))
  }
}))

export {
  useCountState,
  useLanguage,
  useTheme,
  useMeta,
  useMenuKey,
  useRefresh,
  useAppConfig,
  useUserAuth,
  useMailTypeOptions,
  useMailTemplates,
  useCookies,
  useLog
}